<?php
namespace Mobile\Controller;
use Mobile\Service\UserService;
class LoginController extends BaseController {
    public $smscodeModel;
    public function __construct() {
        parent::__construct();
        $this->smscodeModel = new \Mobile\Model\smscodeModel();
    }

    public function app () {
        if(get('quit')) {
            session_destroy();
        }
        if(IS_AJAX) {
            $data = $_POST;
            $code = $data['code'];
            if(!$code) {
                return_json(1,'登录失败');
            }
            $uid = UserService::S()->getUidByCode($code);
            if($uid) {
                _login($uid);
                return_json(0,'登录成功');
            }else{
                return_json(1,'登录失败');
            }
        }
        $seo = array(
            'title' => '用户登录'
        );
        $this->setSeo($seo);
        layout('Common/layout-vue');
        $this->display('mylogin');
    }

    public function mobilelogin () {
        $seo = array(
            'title' => '用户登录'
        );
        $this->setSeo($seo);
        layout('Common/layout-vue');
        $this->display();
    }

    public function appmobile () {
        if(IS_AJAX) {
            $data = $_POST;
            if(!$data['mobile']||!$data['code']) {
                return_json(1,'请填写完整');
            }
            if($data['mobile']=='18516724903'&&$data['code']=='123456') {

            }else{
                if(!checksmscode($data['mobile'],$data['code'])) {
                    return_json(1,'验证码错误');
                }
            }
            
            $member = $this->memberModel->where(array('mobile'=>$data['mobile']))->find();
            if(!$member) {
                //return_json(1,'用户不存在或验证码错误');
                //写入用户
                $new = array(
                    'mobile' => $data['mobile'],
                    'regfrom' => 'app_mobile',
                    'create_time' => date('Y-m-d H:i:s')
                );
                $res = $this->memberModel->add($data);
                if($res) {
                    $member['uid'] = $res;
                }else{
                    return_json(0,'网络错误请重试');
                }
            }
            _login($member['uid']);
            if(!$member['refer_uid']) {
                return_json(0,'登录成功','','/mobile/index/bindrefer');
            }
            return_json(0,'登录成功','','/mobile/index');
        }
    }

    public function index(){
        if(IS_AJAX){
            $uid = get('uid');
            $pw = get('pw');
             $len = strlen($uid);
            if($len>=11){
                $where = array(
                    'mobile' => $uid,
                );
            }else{
                $where = array(
                    'uid' => $uid,
                );
            }
            $res = $this->memberModel->where($where)->find();
            if(!$res) {
                return_json(1,'密码不正确');
            }
            if($res['try_time']>=30) {
                return_json(1,'禁止登录');
            }
            $pw = md5($pw.C('SALT'));
            if($res['password']!=$pw) {
                $this->memberModel->where($where)->setInc('try_time');
                return_json(1,'密码不正确');
            }
            
            $this->memberModel->where($where)->setField('try_time',0);
            
            if(!$res){
                return_json(1,'密码不正确');
            }else{
                session('memberinfo',$res);
                session('uid',$res['uid']);
                parent::autoLogin(true);
                return_json(0,"登录成功","","/mobile/user");
            }
        }
        $seo_data = array(
            "title" => C('SITE_NAME'),
            "keywords" => "",
        );
        $this->setSeo($seo_data);
//        layout(false);
        $this->display();
    }
    
    public function changepw() {
        if (IS_AJAX) {
            $allow = array('password_old', 'password_new1', 'password_new2');
            $data = param_filter($_POST, $allow);

            if (!$data['password_old']) {
                return_json(1, "请输入旧密码");
            }

            if (!$data['password_new1']) {
                return_json(1, "请输入新密码");
            }

            if (!$data['password_new2']) {
                return_json(1, "请确认新密码");
            }

            if ($data['password_new1'] != $data['password_new2']) {
                return_json(1, "两次输入密码不一致");
            }

            $uid = session('uid');

            if (!$uid) {
                session_destroy();
                return_json(0, "请先登录", '', "/mobile/login/");
            }

            $res = $this->memberModel->where(array('uid' => $uid))->getField('password');
            if ($res != md5($data['password_old'].C("SALT"))) {
                return_json(1, "旧密码输入错误");
            }
            checkPassword($data['password_new1']);
            $pw = md5($data['password_new1'].C('SALT'));
            $res = $this->memberModel->where(array('uid' => $uid))->setField('password', $pw);

            if ($res) {
                session_destroy();
                return_json(0, "修改成功,请重新登录", '', "/mobile/login/");
            } else {
                return_json(1, "网络错误");
            }
        }
        $seo_data = array(
            "title" => '修改密码',
            "description" => "",
            "keywords" => "",
        );
        layout('Mui/layout');
        $this->setSeo($seo_data);
        $this->display();
    }

    public function quit(){
        session_destroy();
        header('Location: /mobile/login/app?quit=1');
    }
    
     public function resetpw() {
        
        if(IS_AJAX){
            $allow = array(
                'mobile','smscode','code_id','password'
            );
            $data = param_filter($_POST, $allow);
            $where = array(
                'mobile'=>$data['mobile'],
            );
            $member = $this->memberModel->where($where)->find();
            
            if(!$member) {
                return_json(1,'用户不存在');
            }
            
            if(strlen($data['password'])<6) {
                return_json(1,'密码必须大于6位');
            }
            checkPassword($data['password']);
//            _pr($data['password']);
            $this->_checkCode($data);
            $saveData = array(
                'password' => md5($data['password'].C('SALT')),
                'try_time' => 0
            );
            $res = $this->memberModel->where($where)->save($saveData);
            if($res) {
                return_json(0,'修改成功','','/mobile/login');
            }
            return_json(1,'密码与旧密码相同');
            
        }
        $seo_data = array(
            "title" => '忘记密码',
            "description" => "",
            "keywords" => "",
        );
//        layout('Mui/layout');
        $this->setSeo($seo_data);
        $this->display('resetpw');
    }


    /*
     * 发送手机验证码
     */
    public function sendsms(){
        $mobile = get('mobile');
        if(!check_mobile($mobile)){
            return_json(1,"请检查手机号是否正确");
        }
        if(sendsmscode($mobile)) {
            return_json(0,'发送成功');
        }
    }
    
    
    protected function _checkCode($data){
        if(!$data['code']) {
            return_json(1,'请输入验证码');
        }
        //检查验证码是否正确
        $codewhere = array(
            "code_id" => $data['code_id'],
            "code" => $data['code'],
            "mobile" => $data['mobile'],
        );
        $code_id = $data['code_id'];
        $res = $this->smscodeModel->where($codewhere)->find();
        if(!$res){
            //将尝试次数加1
            $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
            return_json(1,"验证码错误");
        }
        
      //  if($res['ip'] != $ip){
          //  $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
          //  return_json(1,"你的网络有风险,已阻止此次验证!");
     //   }
        
        if(strtotime($res['expired_time']) < time()){
            return_json(1,"验证码已过期,请重新获取!");
        }
        
        if($res['try_time'] > 2){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        if($res['status'] != 1){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        //验证通过
        //将验证码作废
        $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
        $this->smscodeModel->where(array("code_id"=>$code_id))->setField('status',0);
        return true;
        
    }

    public function register () {
        if(IS_AJAX) {
            $allow = array(
                'mobile','code','password'
            );
            $must = array(
                'mobile','code','password'
            );
            $data = param_filter($_POST, $allow,$must,false,true);
            if(empty($data)) {
                return_json(1,'请填写完整');
            }
            if(!checksmscode($data['mobile'],$data['code'])) {
                return_json(1,'验证码错误');
            }
            
            $memberModel = M('member');
            $where = array('mobile'=>$data['mobile']);
            $om = $memberModel->where($where)->find();
            if($om) {
                return_json(1,'手机号已存在');
            }
            $data['password'] = md5($data['password'].C('SALT'));
            $data['create_time'] = date('Y-m-d H:i:s');
            $data['regfrom'] = 'app_mobile';
          
            $res = $memberModel->add($data);
            if($res) {
                _login($res);
                return_json(0,'注册成功');
            }
            return_json(1,'提交失败，请重试');
        }


        // $gradearr = M('grade')->field('grade_id,grade_name')->select();
        // $this->assign('gradearr',$gradearr);
        $seo_data = array(
            "title" => '注册',
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $this->display();
    }
    
    public function upload() {
        $type = 'admin';
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     15145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =  "/";
        $upload->savePath  = "/upload/".$type."/";
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            return_json(0,'',$info['upfile']['savepath'].$info['upfile']['savename']);
        }
    }
  
    public function checkLogin () {
        if(session('uid')) {
            return_json(0,'',session('uid'));
        }else{
            return_json(1,'');
        }
    }

    public function tokenLogin () {
        $token = get('token');
		if($token) {
			$memberinfo = M('member')->where(array('token'=>$token))->find();
			if($memberinfo && $memberinfo['token_expire']>time()) {
                _login($memberinfo['uid']);
                return_json(0,'success');
			}else{
                cookie('token',null);
                return_json(1,'fail');
            }
		}
    }

    public function faxian () {
        $seo = array(
            'title' => '发现'
        );
        if(session('uid')==55308) {
            $this->display('copy');exit;
        }
        $this->setSeo($seo);
        $this->display();
    }
 
}